package test.demo.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
//import java.io.PrintWriter;
import java.net.Socket;

/**
 * @author Hinsteny
 * @date 2016/5/24
 * @copyright: 2016 All rights reserved.
 */
public class BioClient {

	private static class Worker implements Runnable {

		private String address = "localhost";
		private int port = 7777;
		
		public Worker() {
			super();
		}

		@Override
		public void run() {
			Socket socket = null;
			BufferedReader reader = null;
//			PrintWriter writer = null;
			OutputStream outputStream = null;
			try {
				// 创建一个Socket并连接到指定的目标服务器
				socket = new Socket(address, port);
				reader = new BufferedReader(new InputStreamReader(System.in));
//				writer = new PrintWriter(socket.getOutputStream());
				outputStream = socket.getOutputStream();
				String message = reader.readLine(); // 没有内容会阻塞
				do{
//					writer.println(message);
					outputStream.write(message.getBytes());
					message = reader.readLine();
				}while(!message.equals("exit"));
//				writer.flush();
				outputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
//					if (writer != null) {
//						writer.close();
//					}
					if (outputStream != null) {
						outputStream.close();
					}
					if (reader != null) {
						reader.close();
					}
					if (socket != null) {
						socket.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
        //种20个线程发起Socket客户端连接请求
        for(int i=0; i<1; i++){
            new Thread(new Worker()).start();
        }  
	}
}